package com.KKd.pojo.builder;

import com.KKd.pojo.Comment;
import com.KKd.pojo.dto.NoteDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 14587
 * @date 2021/04/19 12:54
 */
@Component
public class CommentBuilder {

    public List<NoteDTO> buildNoteDTOs(List<Comment> comments){
        //TODO : 构建DTO返回前端
        return null;
    }
    /**
     * 注意这里只转换成2层树
     */
    public List<Map<String, Object>> transform2Tree(List<NoteDTO> notes) {
        if (CollectionUtils.isEmpty(notes)) {
            return Collections.emptyList();
        }
        List<NoteDTO> roots = notes.stream()
                .filter(s -> s.getParentId() == null)
                .sorted(Comparator.comparing(NoteDTO::getCreatedAt).reversed())
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(roots)) {
            return Collections.emptyList();
        }
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

        for (NoteDTO root : roots) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("note", root);

            List<NoteDTO> children = notes.stream()
                    .filter(s -> Objects.equals(root.getId(), s.getParentId()))
                    .sorted(Comparator.comparing(NoteDTO::getCreatedAt))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(children)) {
                result.put("children", children);
            }
            results.add(result);
        }
        return results;
    }
}
